<template>
  <div class="companys-list">
    <el-card class="box-card">
      <!-- 第一列 -->
      <el-form ref="form" :model="form" label-width="80px" label-position="right">
        <el-row>
          <!-- 标签名称输入框 -->
          <el-col :span="6">
            <el-form-item label="标签名称" prop="tags">
              <el-input v-model="form.tags" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <!-- 城市选择器 -->
          <el-col :span="6">
            <el-form-item label="城市" prop="province">
              <el-select v-model="form.province" placeholder="请选择" @change="provinceClick(form.province)">
                <el-option v-for="(item, index) in provinces" :key="index" :value="item"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 地区选择器 -->
          <el-col :span="6">
            <el-form-item label="地区" prop="city">
              <el-select v-model="city" placeholder="请选择">
                <el-option v-for="(item, index) in citys" :key="index" :value="item"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 企业名称输入框 -->
          <el-col :span="6">
            <el-form-item label="企业名称" prop="shortName">
              <el-input v-model="form.shortName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!-- 状态选择器 -->
          <el-col :span="6">
            <el-form-item label="状态" prop="state">
              <el-select v-model="form.state" placeholder="请选择">
                <el-option label="启用" value="1"></el-option>
                <el-option label="禁用" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 清除/搜索按钮 -->
          <el-col :span="12">
            <el-form-item>
              <el-button @click="clear">清除</el-button>
              <el-button type="primary" @click="getCompanyList">搜索</el-button>
            </el-form-item>
          </el-col>
          <!-- 新增用户按钮 -->
          <el-col :span="6">
            <el-button class="el-icon-edit addbtn" type="success" @click="addDialogVisible = true">新增用户</el-button>
          </el-col>
        </el-row>
      </el-form>
      <!-- 提示警告信息 -->
      <el-alert type="info" show-icon :closable="false">
        <template #title>共 {{ companyList.counts }} 条数据</template>
      </el-alert>
      <!-- table数据列表 -->
      <el-table :data="companyList.items" style="width: 100%">
        <el-table-column prop="id" label="序号" width="80" align="center"> </el-table-column>
        <el-table-column prop="number" label="企业编号" width="300" align="center"> </el-table-column>
        <el-table-column prop="shortName" label="企业简称" width="100" align="center"> </el-table-column>
        <el-table-column prop="tags" label="标签" width="80" align="center"> </el-table-column>
        <el-table-column prop="creatorID" label="创建者" align="center" width="100"> </el-table-column>
        <el-table-column prop="remarks" label="备注" width="500" align="center"> </el-table-column>
        <el-table-column label="状态" align="center" width="100">
          <template v-slot="scoped">
            <span v-if="scoped.row.state === 1">启用</span>
            <span v-else>禁用</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200px">
          <template v-slot="scoped">
            <!-- 编辑 -->
            <el-button type="primary" icon="el-icon-edit" size="small" circle plain @click="showEditDialog(scoped.row.id)"></el-button>
            <!-- 修改 -->
            <el-tooltip effect="dark" content="禁用" placement="top" v-if="scoped.row.state === 1">
              <el-button type="warning" icon="el-icon-close" size="small" circle plain @click="reviseList(scoped.row)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="启用" placement="top" v-else>
              <el-button type="success" icon="el-icon-check" size="small" circle plain @click="reviseList(scoped.row)"></el-button>
            </el-tooltip>
            <!-- 删除 -->
            <el-button type="danger" icon="el-icon-delete" size="small" circle plain @click="removeUserById(scoped.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        class="pag"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="form.page"
        :page-sizes="[10, 15, 20, 30]"
        :page-size="form.pagesize"
        layout="prev, pager, next, sizes, jumper"
        :total="companyList.counts"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog title="新增用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
      <!-- 内容主体区域 -->
      <el-form :model="addForm" :rules="FormRules" ref="FormRef" label-width="130px">
        <el-form-item label="企业名称" prop="shortName">
          <el-input v-model="addForm.shortName"></el-input>
        </el-form-item>
        <el-form-item label="所属公司" prop="company">
          <el-input v-model="addForm.company"></el-input>
        </el-form-item>
        <el-form-item>
          <span style="">https://www.tianyancha.com （在此可查询所属公司全称及简称）</span>
        </el-form-item>
        <el-form-item label="城市地区" prop="province">
          <el-select v-model="addForm.province" placeholder="请选择" @change="provinceClick(addForm.province)">
            <el-option v-for="(item, index) in provinces" :key="index" :value="item"> </el-option>
          </el-select>
          <el-select v-model="addForm.city" placeholder="请选择">
            <el-option v-for="(item, index) in citys" :key="index" :value="item"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="方向(企业标签)" prop="tags">
          <el-input v-model="addForm.tags" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="addForm.remarks"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户的对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose">
      <!-- 内容区域 -->
      <el-form :model="editForm" :rules="FormRules" ref="FormRef" label-width="130px">
        <el-form-item label="企业名称" prop="shortName">
          <el-input v-model="editForm.shortName"></el-input>
        </el-form-item>
        <el-form-item label="所属公司" prop="company">
          <el-input v-model="editForm.company"></el-input>
        </el-form-item>
        <el-form-item>
          <span style="">https://www.tianyancha.com （在此可查询所属公司全称及简称）</span>
        </el-form-item>
        <el-form-item label="城市地区" prop="province">
          <el-select v-model="editForm.province" placeholder="请选择" @change="provinceClick(editForm.province)">
            <el-option v-for="(item, index) in provinces" :key="index" :value="item"> </el-option>
          </el-select>
          <el-select v-model="editForm.city" placeholder="请选择">
            <el-option v-for="(item, index) in citys" :key="index" :value="item"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="方向(企业标签)" prop="tags">
          <el-input v-model="editForm.tags" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="editForm.remarks"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { provinces, citys } from '@/views/companys-list/component/citys'
import { getCompanys, addCompanys, getEditCompany, editCompanys, deleteCompanys, stateCompanys } from '@/api/companys-list/companys-list'

export default {
  name: 'companys-list',
  components: {},
  data() {
    return {
      // 企业列表
      companyList: [],
      // 城市数据
      provinces: [],
      // 地区数据
      citys: [],
      // 地区选中的数据
      city: '',
      form: {
        // 当前的页码值
        page: 1,
        // 每页显示多少条数据
        pagesize: 10,
        tags: '',
        // 城市选中的数据
        province: '',
        shortName: '',
        // 设置状态 1：启用 0：禁用
        state: null
      },
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 添加用户的数据
      addForm: {
        isFamous: false,
        shortName: '',
        company: '',
        province: '',
        city: '',
        tags: '',
        remarks: ''
      },
      // 添加/修改用户的验证规则
      FormRules: {
        shortName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
        company: [{ required: true, message: '请输入所属公司', trigger: 'blur' }],
        province: [{ required: true, message: '请选择城市地区', trigger: 'blur' }],
        tags: [{ required: true, message: '请输入企业方向', trigger: 'blur' }],
        remarks: [{ required: true, message: '请输入备注', trigger: 'blur' }]
      },
      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 修改用户的数据
      editForm: {}
    }
  },
  created() {
    this.getprovince()
    this.getCompanyList()
  },
  methods: {
    // 获取城市列表数据
    async getprovince() {
      this.provinces = await provinces()
      // console.log(this.province)
    },
    // 监听选中的城市状态
    async provinceClick(c) {
      console.log(c)
      this.citys = await citys(c)
      // console.log(this.citys)
      // 判断地区列表是否有数据
      if (this.citys !== -1) {
        // 把第一项赋值
        this.city = this.citys[0]
        this.addForm.city = this.citys[0]
        this.editForm.city = this.citys[0]
      } else {
        this.city = []
        this.addForm.city = []
        this.editForm.city = []
      }
    },
    // 获取企业列表
    async getCompanyList() {
      try {
        const { data } = await getCompanys(this.form)
        // console.log(data)
        this.companyList = data
      } catch (err) {
        this.$message.error('获取列表数据失败！')
      }
    },
    // 监听每页显示数据的变化
    handleSizeChange(newSize) {
      this.form.pagesize = newSize
      this.getCompanyList()
    },
    // 监听页码值的变化
    handleCurrentChange(newPage) {
      this.form.page = newPage
      this.getCompanyList()
    },
    clear() {
      this.form = {}
      this.city = ''
      this.getCompanyList()
    },
    // 监听关闭添加用户的对话框实现重置
    addDialogClose() {
      this.$refs.FormRef.resetFields()
    },
    // 点击确定，添加新用户
    addUser() {
      this.$refs.FormRef.validate(async valid => {
        if (!valid) return
        try {
          console.log(this.addForm)
          const data = await addCompanys(this.addForm)
          console.log(data)
          this.$message.success('添加用户成功！')
          // 隐藏添加用户的对话框
          this.addDialogVisible = false
          // 更新页面数据
          this.getCompanyList()
        } catch (err) {
          this.$message.error('添加新用户失败！')
        }
      })
    },
    // 展示修改用户的对话框
    async showEditDialog(id) {
      console.log(id)
      try {
        this.editDialogVisible = true
        const { data: res } = await getEditCompany(id)
        console.log(res)
        this.editForm = res
      } catch (err) {
        this.$message.error('获取用户信息失败！')
      }
    },
    // 监听关闭修改用户对话框实现重置
    editDialogClose() {
      this.$refs.FormRef.resetFields()
    },
    // 监听修改用户信息的提交
    editUser() {
      // 提交之前预验证
      this.$refs.FormRef.validate(async valid => {
        if (!valid) return
        try {
          // 发起修改数据请求
          console.log(this.editForm.id)
          console.log(this.editForm)
          const data = await editCompanys({
            id: this.editForm.id,
            number: this.editForm.number,
            isFamous: false,
            shortName: this.editForm.shortName,
            company: this.editForm.company,
            province: this.editForm.province,
            city: this.editForm.city,
            tags: this.editForm.tags,
            remarks: this.editForm.remarks
          })
          this.editForm = data
          console.log(data)
          // 隐藏添加用户的对话框
          this.editDialogVisible = false
          // 更新页面数据
          this.getCompanyList()
          // 提示信息
          this.$message.success('修改用户信息成功！')
        } catch (err) {
          this.$message.error('修改用户信息失败！')
        }
      })
    },
    // 修改启用禁用
    async reviseList(valueMate) {
      console.log(valueMate)
      const confirmResult = await this.$confirm('已成功禁用, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 确认：confirm  取消：cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消禁用')
      }
      valueMate.state = !valueMate.state
      if (valueMate.state === true) {
        valueMate.state = 1
      }
      try {
        // 调用接口更改数据
        await stateCompanys(valueMate)
        this.$message.success('禁用成功!')
        // 更新页面数据
        // this.getCompanyList()
      } catch (error) {
        this.$message.error('error')
      }
    },
    // 删除用户
    async removeUserById(id) {
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 确认：confirm  取消：cancel
      console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      // 调用接口删除数据
      const { data: res } = await deleteCompanys(id)
      console.log(res)
      this.$message.success('删除用户成功!')
      // 更新页面数据
      this.getCompanyList()
    }
  }
}
</script>

<style lang="less" scoped>
.companys-list {
  .el-col {
    float: left;
    .el-form-item {
      width: 100%;
    }
    .addbtn {
      float: right;
    }
  }
  .pag {
    float: right;
    margin: 20px 0;
  }
  .buttom {
    height: 150px;
  }
}
</style>
